package com.newstart.timetask.project.utils.timeTask;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2017/9/29.
 */
public class TaskManager {
    /**
     * 开启任务
     */
    //默认时间间隔一小时
    private static long PERIOD_TIME = 1 * 1 * 1 * 1000;
    Log log = LogFactory.getLog(TaskManager.class);
 
    public void startTask(TimerTask task, int dayInterval, int hour, int minute){
        PERIOD_TIME =  dayInterval *1 * 1 * 1 * 1000;
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, 0);
        //执行定时任务的时间
        Date date=calendar.getTime();
        //为了避免若容器启动的时间晚于定时时间，在重启容器的时候会立刻执行该任务
        if (date.before(new Date())) {
            date = this.addDay(date, 1);
        }
        Timer timer = new Timer();
        //任务在指定的时间开始进行重复的固定延迟执行
        timer.schedule(task,date,PERIOD_TIME);
 
      
    }
    // 增加或减少天数
    public Date addDay(Date date, int num) {
        Calendar startDT = Calendar.getInstance();
        startDT.setTime(date);
        startDT.add(Calendar.DAY_OF_MONTH, num);
        return startDT.getTime();
    }
}

